/**
 * axios 二次封装
 */

import axios from "axios";
import config from "../config";
import { ElMessage } from "element-plus";
import router from "../router";
import storage from "./storage";

const TOKEN_INVALID = "TOKEN 错误,请重新登录";
const NETWORK_ERROR = "网络异常,请稍后重试";
// axios 实例对象
const service = axios.create({
  baseURL: config.baseApi,
  timeout: 8000, // 8s
});

// 请求拦截
service.interceptors.request.use((req) => {
  const headers = req.headers;
  if (storage.getItem("userInfo")) {
    const { token } = storage.getItem("userInfo");
    if (!headers.Authorization) headers.Authorization = "Bearer " + token;
  }

  return req;
});

// 相应拦截
service.interceptors.response.use((res) => {
  const { code, data, msg } = res.data;
  // console.log('request返回拦截,code=', code,',msg=',msg,',data=',data)
  if (code === 200) {
    return data;
  } else if (code === 40001) {
    // token出错
    ElMessage.error(TOKEN_INVALID);

    setTimeout(() => {
      router.push("/login");
    }, 5000);
    return Promise.reject(TOKEN_INVALID);
  } else {
    ElMessage.error(msg || NETWORK_ERROR);
    return Promise.reject(msg || NETWORK_ERROR);
  }
});

// 请求函数
function request(options) {
  // 处理 GET 请求的params
  options.method = options.method || "get";
  if (options.method.toLowerCase() === "get") {
    options.params = options.data;
  }

  let isMock = config.mock;
  if (typeof options.mock != "undefined") {
    isMock = options.mock;
  }

  // 处理prod
  if (config.env === "prod") {
    service.defaults.baseURL = config.baseApi;
  } else {
    service.defaults.baseURL = isMock ? config.mockApi : config.baseApi;
  }
  console.log(
    "🚀 ~ file: request.js api 请求地址为 => ",
    service.defaults.baseURL,
    "请求的参数为: data => ",
    options.data
  );
  return service(options);
}

["get", "post", "put", "delete", "patch"].forEach((item) => {
  request[item] = (url, data, options) => {
    return request({ url, method: item, data, ...options });
  };
});

export default request;
